package ai4games_tests.tests;

import java.util.Set;

import game2dai.Domain;
import game2dai.World;
import game2dai.entities.MovingEntity;
import game2dai.entities.Wall;
import game2dai.entityshapes.ps.ArrowPic;
import game2dai.entityshapes.ps.WallPic;
import game2dai.maths.Vector2D;
import game2dai.steering.SBF;
import game2dai.utils.StopWatch;
import processing.core.PApplet;

public class BulletWallTest extends PApplet  {

	World world;
	Domain domain;
	Bullet bullet;
	ArrowPic bulletView;
	StopWatch watch;
	float bulletSpeed = 400;
	
	public void setup(){
		size(600, 400);
		world = new World(width, height);
		domain = new Domain(0,0,width,height);
		bulletView = new ArrowPic(this, 14, color(255,80,80), color(128,0,0),1);
		makeWalls();
		watch = new StopWatch();
	}

	public void draw(){
		float deltaTime = (float) watch.getElapsedTime();
		if(bullet != null){
			Set<Wall> walls = world.getWalls(bullet);
			for(Wall w : walls){
				if(bullet.hasPassedThroughWall(w)){
					bullet.velocity(0, 0);
					bullet.die(world, 3);
					bullet = null;
					break;
				}
			}
		}
		background(220, 255, 220);
		fill(240,240,255);
		stroke(0,0,128);
		ellipse(width/2, height/2,5,5);
		world.update(deltaTime);
		world.draw();
	}

	public void mouseClicked(){
		if(bullet == null){
			Vector2D dir = new Vector2D(mouseX - width/2, mouseY-height/2);
			dir.normalize();
			Vector2D vel = Vector2D.mult(dir, bulletSpeed);
			bullet = new Bullet(new Vector2D(width/2, height/2), 6, vel, bulletSpeed, dir, 1, 12, 200);
			bullet.renderer(bulletView);
			bullet.worldDomain(domain);
			bullet.worldDomainConstraint(SBF.REBOUND);
			world.add(bullet);
		}
	}
	
	public void makeWalls(){
		int[] x = {  80, 200,  50, 140, 200, 240, 400, 400, 400, 550, 550, 550, 340, 530 };
		int[] y = { 100,  50, 350, 190, 300, 330,  70, 130, 100,  50,  110, 280, 260, 320 };
		for(int n = 0; n < x.length - 1; n+=2){
			WallPic wp = new WallPic(this, color(0,0,128), 2);
			Wall w = new Wall(new Vector2D(x[n], y[n]), new Vector2D(x[n+1], y[n+1]), true);
			w.renderer(wp);
			world.add(w);
		}
	}

	public class Bullet extends MovingEntity {

		public Bullet(Vector2D position, double radius,
				Vector2D velocity, double max_speed, Vector2D heading,
				double mass, double max_turn_rate, double max_force) {
			super(position, radius, velocity, max_speed, heading, mass,
					max_turn_rate, max_force);
		}

		public boolean hasPassedThroughWall(Wall wall){
			return wall.isEitherSide(prevPos, pos);
		}

	}
}
